import os

from django.conf import settings
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from articles.models import Article, ArticlCategory
from bigevent_admin.serializers.articles import ArticleCategoriesSerializer, ArticleSerializer
from utils.PagePaginator import ArticePageNum
from utils.jwt_utils import get_user


class ArticleCategoriesView(ModelViewSet):
    queryset = ArticlCategory.objects.all()
    serializer_class = ArticleCategoriesSerializer
    pagination_class = ArticePageNum
    # permission_classes = [IsAuthenticated]
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({
                          "status": 0,
                          "message": "新增文章分类成功！"
                        })
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({
                          "status": 0,
                          "message": "删除文章分类成功！"
                        })

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({
                          "status": 0,
                          "message": "获取文章分类数据成功！",
                          "data":serializer.data
                        })

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        cate_id = request.data.get('id')
        instance = ArticlCategory.objects.get(id=cate_id)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response({
                          "status": 0,
                          "message": "更新分类信息成功！"
                        })


class ArticleView(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = ArticePageNum
    def get_queryset(self):
        get_cate_id = self.request.query_params.get('cate_id',None)
        get_state = self.request.query_params.get('state',None)
        if get_cate_id and get_state:
            return self.queryset.filter(cate_name_id=get_cate_id,state =get_state)
        elif get_cate_id or get_state:
            if get_cate_id:
                return self.queryset.filter(cate_name_id=get_cate_id)
            else:
                return self.queryset.filter(state =get_state)
        else:
            return self.queryset


    def create(self, request, *args, **kwargs):
        # data = request.POST
        # print(data)
        file = request.FILES.get('cover_img')
        cate_id = request.data.get('cate_id')
        state = request.data.get('state')
        title = request.data.get('title')
        content = request.data.get('content')
        cover_img = request.data.get('cover_img')
        filename =cover_img.name
        user = get_user(request)
        data = {
            'cover_img':file.name,
            'cate_name' :ArticlCategory.objects.get(id=cate_id),
            'cate_name_id': cate_id,
            'state':state,
            'title' :title,
            'content':content,
            'author' :user.id,
            'cover_img':cover_img
        }
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response({
                            'status': 0,
                            'message': '发布文章成功！'
                        })
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({
                          "status": 0,
                          "message": "删除文章成功！"
                        })

    def retrieve(self, request, *args, **kwargs):
        print(request.data)
        print(request.query_params)
        pk = request.META.get('HTTP_REFERER').split('?id=', 1)[1]
        instance = Article.objects.get(id=pk)
        serializer = self.get_serializer(instance)
        response= {
                          "status": 0,
                          "message": "获取文章数据成功！",
                          "data":serializer.data
                        }
        response['data']['cover_img']=os.path.join(settings.QINIU_BASE_URL,instance.cover_img.name)
        return Response(response)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        cate_id = request.data.get('id')
        instance = ArticlCategory.objects.get(id=cate_id)
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}

        return Response({
                          "status": 0,
                          "message": "更新文章信息成功！"
                        })